package com.java.advance.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.client.loadbalancer.ServiceInstanceChooser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by yangminghua on 2019/3/18.
 */
@RestController
public class ClientController {

//    @Autowired
//    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping(value = "/getProductList")
    public String getProductList() {
        //1、第一种方式(直接使用RestTemplate，url写死)
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject("http://localhost:9001/list", String.class);

        //2、第二种方式(利用LoadBalancerClient通过应用名获取url，然后在使用直接使用RestTemplate)
//        RestTemplate restTemplate = new RestTemplate();
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
//        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/list");
//        String response = restTemplate.getForObject(url, String.class);

        //3、第三种方式(利用@LoadBalanced通过应用名获取url，可在RestTemplate中使用应用名字)
        String response = restTemplate.getForObject("http://PRODUCT/list", String.class);
        System.out.println(response);
        return response;

    }
}
